package cn.com.xy.sms.sdk.db.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.ContentValues;
import android.util.LruCache;
import cn.com.xy.sms.sdk.db.DBManager;
import cn.com.xy.sms.sdk.db.XyCursor;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.util.StringUtils;

/* SDK-681 zhaojiangwei 20161121 start */

public class PhoneNumServeManager {
    public static final String ID = "id";  
    public static final String PHONE_NUM = "phoneNum";
    public static final String AREA_CODE = "areaCode";
    public static final String JSON_RESULT = "jsonResult";
    public static final String UPDATETIME = "updateTime";
    public static final String STATUS = "status";
    public static final String VERSION = "version";
    public static final String QUERY_KEY = "queryKey";
    
    public static final String TABLE_NAME = "tb_phonenum_menu";
    
    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;
    public static final String CREATE_TABLE = "create table  if not exists "  + TABLE_NAME + " ("
                                                                 + ID + " INTEGER PRIMARY KEY," 
                                                                 + QUERY_KEY + " TEXT unique,"
                                                                 + PHONE_NUM+" TEXT,"
                                                                 + AREA_CODE +" TEXT,"
                                                                 + JSON_RESULT +" TEXT,"
                                                                 + STATUS+" INTEGER DEFAULT '1',"   
                                                                 + VERSION + " TEXT,"
                                                                 + UPDATETIME+" INTEGER DEFAULT '0'"
                                                                 + ")";
    
    public static final String QUERY_KEY_FMT = "%s:%s";
    
    public static long insertOrUpdate(String phoneNum, String areaCode, JSONObject result, long lastQueryTime) {
        long opRet = -1;
        if (result == null || StringUtils.isNull(phoneNum)) {
            return opRet;
        }
        if (StringUtils.isNull(areaCode)) {
            areaCode = "CN";
        }
        String queryKey = String.format(QUERY_KEY_FMT, phoneNum, areaCode);
        int status = result.optInt("status");
        String version = result.optString("version");
        XyCursor xyCursor = null;
        ContentValues values = new ContentValues();
        values.put(PHONE_NUM, phoneNum);
        values.put(STATUS, status);
        values.put(AREA_CODE, areaCode);
        values.put(JSON_RESULT, result.toString());
        values.put(VERSION, version);
        values.put(QUERY_KEY, queryKey);
        values.put(UPDATETIME, lastQueryTime);
        values.put(STATUS, status);

        try {
            String selection = QUERY_KEY + " = ?";
            String whereArgs[] = new String[] { queryKey };

            xyCursor = DBManager.query(TABLE_NAME, null, selection, whereArgs);
            if (xyCursor != null && xyCursor.getCount() > 0) {
                opRet = DBManager.update(TABLE_NAME, values, selection, whereArgs);
            }
            else {
                opRet = DBManager.insert(TABLE_NAME, values);
            }
        }
        catch (Throwable e) {
            // TODO Auto-generated catch block
            LogManager.e("phonemenu", "PhoneNumMenuManager.insertOrUpdate error", e);
        }
        finally {
            XyCursor.closeCursor(xyCursor, true);
        }
        return opRet;
    }
    
    public static long updateLastCheckTime(List<PhoneNumServe>phoneMenus, long lastQueryTime ){
    	if (phoneMenus==null || lastQueryTime<=0) {
			return -1;
		}
    	 XyCursor xyCursor = null;
         ContentValues values = new ContentValues();
         values.put(UPDATETIME, lastQueryTime);
         
        int count = phoneMenus.size();
     	String whereArgs[] = new String[count];
     	for(int index=0; index<count; index++ ){
     		PhoneNumServe phoneItem = phoneMenus.get(index);
     		whereArgs[index] = String.format(QUERY_KEY_FMT, phoneItem.phoneNum, phoneItem.areaCode);
     	}
     	String placeholders = SmsParseRecorder.makePlaceholders(count);
        String selection = QUERY_KEY + " IN (" + placeholders + ")";
        long opRet = -1;
        try {
        	opRet = DBManager.update(TABLE_NAME, values, selection, whereArgs);
        }
        catch (Throwable e) {
            // TODO Auto-generated catch block
            LogManager.e("phonemenu", "PhoneNumMenuManager.insertOrUpdate error", e);
        }
        finally {
            XyCursor.closeCursor(xyCursor, true);
        }
        return opRet;
    }
    
    public static PhoneNumServe queryMenuResult(String phoneNum, String areaCode) {
        PhoneNumServe opResponse = null;
        if (StringUtils.isNull(phoneNum)) {
            return opResponse;
        }
        if (StringUtils.isNull(areaCode)) {
            areaCode = "CN";
        }
        XyCursor cur = null;
        try {  
        	String queryKey = String.format(QUERY_KEY_FMT, phoneNum, areaCode);
            String selection = QUERY_KEY + " = ?";
            String whereArgs[] = new String[] { queryKey };
            
            cur = DBManager.query(TABLE_NAME,  null, selection, whereArgs);
            if (cur != null && cur.getCount() > 0) {
                opResponse = new PhoneNumServe();
                opResponse.areaCode = areaCode;
                opResponse.phoneNum = phoneNum;
                
                int resultIndex = cur.getColumnIndex(JSON_RESULT);
                int statusIndex =  cur.getColumnIndex(STATUS);
                while (cur.moveToNext()) {
                    opResponse.status = cur.getInt(statusIndex);
                    opResponse.jsResult = cur.getString(resultIndex);
                    break;
                }
            }
        }
        catch (Throwable e) {
            // TODO: handle exception
            LogManager.e("phonemenu", "PhoneNumMenuManager.queryMenuResult error", e);
        }
        finally {
            XyCursor.closeCursor(cur, true);
        }
        return opResponse;
    }
    
    public static Map<String, JSONObject> queryMenuResult(List<String>phoneNums, String areaCode, LruCache<String, JSONObject> luCache) {
    	Map<String, JSONObject>results  = new HashMap<String, JSONObject>();
		if (phoneNums==null || phoneNums.size()==0) {
            return results;
        }
        if (StringUtils.isNull(areaCode)) {
            areaCode = "CN";
        }
        XyCursor cur = null;
        try {  
        	int count = phoneNums.size();
        	String queryKeys[] = new String[count];
        	for(int index=0; index<count; index++ ){
        		String phone = StringUtils.getPhoneNumberNo86(phoneNums.get(index));
        		queryKeys[index] = String.format(QUERY_KEY_FMT, phone, areaCode);
        	}
        	String placeholders = SmsParseRecorder.makePlaceholders(count);
            String whereClause = QUERY_KEY + " IN (" + placeholders + ")";
            
            cur = DBManager.query(TABLE_NAME,  null, whereClause, queryKeys);
            if (cur != null && cur.getCount() > 0) {
				int indexResult = cur.getColumnIndex(JSON_RESULT);
				int indexQuery = cur.getColumnIndex(QUERY_KEY);
                while (cur.moveToNext()) {
                	String key = cur.getString(indexQuery);
                	JSONObject objectItem = new JSONObject(cur.getString(indexResult));
                	
                	results.put(key, objectItem);
                	if (luCache!=null) {
                		luCache.put(key, objectItem);
					}
                }
            }
        }
        catch (Throwable e) {
            // TODO: handle exception
            LogManager.e("phonemenu", "PhoneNumMenuManager.queryMenuResult error", e);
        }
        finally {
            XyCursor.closeCursor(cur, true);
        }
		
		return results;
    }
    
    
    public static List<PhoneNumServe> queryPhoneAndAreaCodes(long offsetTime, int status) {
		XyCursor cursor = null;
		List<PhoneNumServe>results  = new ArrayList<PhoneNumServe>();
		try {
			String where = "updateTime < ? and status = ?";
			String args[] = new String[] { String.valueOf(offsetTime), String.valueOf(status) };
			
			String[] cols = new String[] { "phoneNum", "areaCode", "version" };
			cursor = DBManager.query(TABLE_NAME, cols, where, args);
			if (cursor != null) {
				int indexPhoneNum = cursor.getColumnIndex("phoneNum");
				int indexArea = cursor.getColumnIndex("areaCode");
				int indexVersion = cursor.getColumnIndex("version");
				while (cursor.moveToNext()) {
					PhoneNumServe phoneItem = new PhoneNumServe();
					phoneItem.phoneNum = cursor.getString(indexPhoneNum);
					phoneItem.areaCode = cursor.getString(indexArea);
					phoneItem.version = cursor.getString(indexVersion);
					
					results.add(phoneItem);
				}
			}
		}
		catch (Throwable e) {
			LogManager.w("phonemenu", "queryPhoneAndAreaCodes: ", e);
		}
		finally {
			XyCursor.closeCursor(cursor, true);
		}
		return results;
	}
}

/* SDK-681 zhaojiangwei 20161121 end */